import React, { Component, Fragment } from 'react';
import { Form, Input, Select, DatePicker, Button, Modal } from 'antd';
import { connect } from 'dva';
import Media from 'react-media';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import StandardTable from '@/components/StandardTable';
import TireDetail from './TireDetail';
import AdSearch from '@/components/AdSearch';
import moment from 'moment';
import router from 'umi/router';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
import { formateDateToMin } from '@/utils/common';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const { Option } = Select;
const confirm = Modal.confirm;

@ManageList
@connect(({ tire, loading, component, common }) => ({
  tire,
  loading: loading.effects['manageEtc/tireList'],
  ownCompany: common.ownCompany,
  searchValue: component.searchValue,
}))
@Form.create()
export default class TireList extends Component {
  state = {
    visible: false,
    id: '',
    formValues: {},
    cars: [],
    expandForm: false,
  };
  className = 'TireList';
  columns = [
    {
      title: '单据号',
      dataIndex: 'tireNo',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record.id)}
          text={text}
          code={codes.showDetail}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '轮胎编号',
      dataIndex: 'code',
      render: text => <span title={text}>{text}</span>,
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'tireObject',
      render: (text, record) => <span>{text ? '可用' : '使用中'}</span>,
      width: 100,
    },
    {
      title: '主车牌',
      dataIndex: 'cartPlateNo',
    },
    {
      title: '所属公司',
      dataIndex: 'ownCompanyName',
      render: text => <span title={text}>{text}</span>,
      width: 250,
    },
    {
      title: '轮胎品牌',
      dataIndex: 'tireBrand',
    },
    {
      title: '当前里程',
      dataIndex: 'currentMileage',
    },
    {
      title: '里程上限',
      dataIndex: 'mileageLimit',
    },
    {
      title: '使用期限',
      dataIndex: 'usePeriod',
    },
    {
      title: '采购价格',
      dataIndex: 'feeCost',
      render: text => {
        return <span>{text && Number(text) !== 0 ? Number(text).toFixed(2) : text}</span>;
      },
    },
    {
      title: '使用人',
      dataIndex: 'usePerson',
    },
    {
      title: '使用地',
      dataIndex: 'useLocation',
    },
    {
      title: '更换日期',
      dataIndex: 'changeTime',
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];

  componentDidMount() {
    this.dispatchFun('tire/tireList', {});
    // this.dispatchFun('tire/carList', { pageSize: 1000 });
  }

  // 分页操作
  handleStandardTableChange = param => {
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.dispatchFun('tire/tireList', params);
  };

  // 重置条件查询表单
  handleFormReset = () => {
    this.setState({ formValues: {}, cars: [] });
    this.dispatchFun('tire/tireList', {});
  };

  toggleForm = expandForm => {
    this.setState({
      expandForm,
    });
  };

  // 执行条件查询表单
  handleSearch = values => {
    const { cars } = this.state;
    if (cars.length > 0) {
      const vehicleId = cars.map(v => {
        return v.id;
      });
      values.vehicleId = vehicleId.join(',');
    } else {
      values.vehicleId = '';
    }
    this.setState({
      formValues: values,
    });
    this.dispatchFun('tire/tireList', values);
  };

  // 跳转 新增页面
  handleAdd = () => {
    const { dispatch } = this.props;
    router.push('/carDaily/tireList/addTire');
  };

  // 跳转 编辑页面
  handleEdit = () => {
    const { id } = this.state;
    this.closeDetail();
    router.push(`/carDaily/tireList/editTire/${id}`);
  };

  // 关闭右抽屉
  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };
  // 打开右抽屉
  showDetail = (e, id) => {
    e.stopPropagation();
    this.setState({
      visible: true,
      id,
    });
    this.dispatchFun('tire/tireDetail', { id });
  };

  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch } = this.props;

    dispatch({
      type: type,
      payload: params,
      callback: data => {
        if (type === 'tire/tireList' && data) {
          let valueList = [];
          data.map(v => {
            const labels = ['updateBy', 'createBy'];
            labels.map(item => {
              if (v[item] && !valueList.includes(v[item])) {
                valueList.push(v[item]);
                !searchValue[v[item]] &&
                  dispatch({
                    type: 'component/querySearchValue',
                    payload: {
                      params: { loginName: v[item] },
                      url: 'tms/tms-vehicle-tire/selectUser_s',
                    },
                  });
              }
            });
          });
        }
      },
    });
  }
  getValue = values => {
    this.setState({
      cars: values,
    });
  };
  //删除
  removeRecord = () => {
    const { dispatch } = this.props;
    const { id, visible, formValues } = this.state;
    confirm({
      title: '确定要删除这条数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'tire/deleteTire',
          payload: { id: id },
          callback: () => {
            this.setState({ visible: false, selectedRows: [] });
            this.dispatchFun('tire/tireList', formValues);
          },
        });
      },
    });
  };

  render() {
    const {
      form,
      loading,
      tire: { tireList, detail, carList },
      isMobile,
      ownCompany,
    } = this.props;
    const { id, visible, expandForm } = this.state;
    const { getFieldDecorator } = form;
    // firstForm 参数
    const firstFormItem = (
      <FormItem label="车牌号">
        {getFieldDecorator('vehicleId')(
          // <Select
          //   allowClear={true}
          //   showSearch
          //   filterOption={(input, option) =>
          //     option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          //   }
          //   placeholder="请选择"
          //   style={{ width: '100%' }}
          // >
          //   <Option value="">请选择</Option>
          //   {carList.list &&
          //     carList.list.map((v, i) => {
          //       return (
          //         <Option key={i} value={v.id}>
          //           {v.cartPlateOneNo}
          //         </Option>
          //       );
          //     })}
          // </Select>
          <SearchSelect
            dataUrl="tms/tms-vehicle-tire/selectVehicle"
            url="tms/tms-vehicle-tire/selectVehicleView_s" // selectedData只只有id时需要传url
            selectedData={this.state.cars} // 选中值
            multiple={false} // 是否多选
            showValue="cartPlateOneNo"
            searchName="cartPlate"
            columns={columns1} // 表格展示列
            onChange={this.getValue} // 获取选中值
            scrollX={480}
            id="tire_1"
          />
        )}
      </FormItem>
    );
    const secondFormItem = (
      <FormItem label="所属公司">
        {getFieldDecorator('ownCompanyId')(
          <Select
            showSearch
            allowClear={true}
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            placeholder="请选择"
            style={{ width: '100%' }}
          >
            <Option value="">请选择</Option>
            {ownCompany.map((v, i) => {
              return (
                <Option key={i} value={v.customerCode}>
                  {v.customerName}
                </Option>
              );
            })}
          </Select>
        )}
      </FormItem>
    );
    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="单据号">
          {getFieldDecorator('tireNo')(<Input placeholder="请输入" />)}
        </FormItem>,
      ],
      ['operatorButtons'],
    ];

    // console.log('---------', codes);
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };

    const tableButtonsParams = {
      show: false,
      code: codes.add,
      handleAdd: this.handleAdd,
    };

    const rightDrawParams = {
      isMobile,
      visible,
      title: '轮胎详情',
      code: codes.showDetail,
      closeDetail: this.closeDetail,
      buttons: (
        <span>
          <AdButton
            onClick={() => this.removeRecord(1)}
            text="删除"
            type="danger"
            ghost
            code={codes.remove}
          />
          <AdButton
            style={{ marginLeft: 8 }}
            onClick={this.handleEdit}
            type="primary"
            text="编辑"
            code={codes.edit}
          />
        </span>
      ),
    };
    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          disabledRowSelected={true}
          loading={loading}
          data={tireList}
          columns={this.columns}
          expandForm={expandForm}
          className={this.className}
          onPaginationChange={this.handleStandardTableChange}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <TireDetail isMobile={isMobile} id={id} />
        </RightDraw>
      </Fragment>
    );
  }
}
